package com.lt.flashcard.view;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.Init;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Messagebox;

import com.lt.flashcard.Utility;
import com.lt.flashcard.model.entity.FlashcardSet;
import com.lt.flashcard.model.service.AAService;
import com.lt.flashcard.model.service.FlashcardSetService;
import com.lt.flashcard.model.service.ImportDataService;
import com.lt.flashcard.model.service.Repository;

public class AdminProductEditVm {

    private FlashcardSet fcs;
    private FlashcardSet proxy;
    private List<String[]> filelist = new ArrayList<String[]>();

    private String oldName = "";

    private final String IMPORT_PATH = Utility.getWebAppPath()
            + Utility.getConfiguration("com.lt.flashcard.flashcardFilesToImportFolder", "files_to_import");

    @Init
    public void init() {
        AAService srv = Repository.getInstance().getAAService();
        if (!srv.isLogin() || !srv.hasRole("admin")) {
            Utility.adminLoginOrAccessDenied(false);
        }

        String strId = Executions.getCurrent().getParameter("id");
        Long id = 0l;
        try {
            id = Long.parseLong(strId);
        } catch (Exception e) {
        }

        if (id.equals(0l)) {
            fcs = new FlashcardSet();
        } else {
            FlashcardSetService fsrv = Repository.getInstance().getFlashcardSetService();
            fcs = fsrv.findByID(id);
        }

        if (fcs == null) {
            Utility.display404(false);
        }

        oldName = fcs.getName();

        fcs.getFlashcards().size();

        buildFileList();
    }

    @Command
    public void save(@BindingParam("import") Listitem selectedImport) {
        FlashcardSetService fsrv = Repository.getInstance().getFlashcardSetService();

        // check valid flashcardset name
        if (!oldName.equals(fcs.getName()) && fsrv.isDupplicateFlashcardSetName(fcs.getName(), fcs.getId(), fcs.getAdmin() == FlashcardSet.ADMIN_YES)) {
            Messagebox.show("Dupplicate flashcardset name");
            return;
        }

        if (fcs.getId() == null) { // new case
            proxy = fcs;
        } else {
            proxy = fsrv.findByID(fcs.getId());
            proxy.setName(fcs.getName());
            proxy.setStoredetail(fcs.getStoredetail());
        }

        if (selectedImport != null) {
            String rs = doImport((String) selectedImport.getValue());
            if (!Utility.isEmptyString(rs)) {
                Messagebox.show(rs);
                return;
            }
        }
        proxy.setReadysale((byte) 1);
        proxy.setAdmin(FlashcardSet.ADMIN_YES);
        proxy.setAuthor(Utility.getUser());
        proxy.setReadysale((byte) 1);
        proxy.setAdmin(FlashcardSet.ADMIN_YES);
        proxy.setStatus(FlashcardSet.STATUS_VALID);
        fsrv.save(proxy);
        Utility.redirect("admin_product_manager.zul", true);
    }

    public void buildFileList() {
        filelist.clear();
        File[] files = new File(IMPORT_PATH).listFiles();
        Arrays.sort(files);
        for (File f : files) {
            if (f.getName().toLowerCase().endsWith(".xls")) {
                filelist.add(new String[] { f.getName(), f.getAbsolutePath() });
            }
        }
    }

    /**
     * Do import data, return false on failure, true otherwise
     * @param filename
     * @return
     */
    public String doImport(String filename) {
        String rs = "";

        ImportDataService srv = Repository.getInstance().getImportDataService();

        try {
            rs = srv.importFlashcardFromExcel(filename, proxy);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return rs;
    }

    public FlashcardSet getFcs() {
        return fcs;
    }

    public void setFcs(FlashcardSet fcs) {
        this.fcs = fcs;
    }

    public List<String[]> getFilelist() {
        return filelist;
    }

    public void setFilelist(List<String[]> filelist) {
        this.filelist = filelist;
    }

    /**
     * @return the proxy
     */
    public FlashcardSet getProxy() {
        return proxy;
    }

    /**
     * @param proxy the proxy to set
     */
    public void setProxy(FlashcardSet proxy) {
        this.proxy = proxy;
    }
}
